/*!
 * vinculum
 * Copyright(c) 2017 azzly
 * MIT Licensed
 */
 
'use strict';

/**
 * Module dependencies.
 * @private
 */
 
const helper = require("./helper");
const CONST = require("./CONST");
const debug = require("./debug")(__filename);
const error = require('./HTTPErrors');
const HTTPError = require('./HTTPError');

class Response{
  constructor(res,req){
    this._origin_response = res;
    this.restype = 'json';
    this.hasSent = false;
  }
  
  send(...args){
    if(this.hasSent){
			console.error(`response has sent`,...args);
      return;
    }
    this.hasSent = true;
    let [statusCode,contentType,content,statusMessage] = [404,'text/html; charset=utf-8','<h1>HTTP 404 Not Found!</h1>',''];
    let len = args.length;
    if(len>0){
      if(typeof args[0] === 'number' && args[0] < 600 && args[0] >= 200){
        statusCode = args[0];
        if(args[1]) content = args[1];
        if(args[2]) contentType = args[2];
        if(args[3]) statusMessage = args[3];
      }else{
        statusCode = 200;
        if(args[0]) content = args[0];
        if(args[1]) contentType = args[1];
      }
    }
    if(statusCode >= 400){
      this._origin_response.writeHead(statusCode,statusMessage, {'Content-Type': contentType});
    }else{
      this._origin_response.writeHead(statusCode, {'Content-Type': contentType});
    }
    
    if(this.session){
      this.session.save().then(result=>{
        this._origin_response.end(content);
      }).catch(err=>{
				this.error(error.SESSION_SAVE_FAILED);
        console.error(`session save error: `,err);
      });
    }else{
      this._origin_response.end(content);
    }
  }
  
  error(err){
    let [statusCode,contentType,content,statusMessage] = [500,'text/html; charset=utf-8','<h1>HTTP 500 Server Error!</h1>','Internal Server Error'];
    if(err instanceof HTTPError){
      statusCode = err.code;
      content = `<h1>HTTP ${statusCode} Server Error(${err.message})!</h1>`;
      statusMessage = err.message;
    }else{
      statusCode = 599;
      content = err;
      statusMessage = 'Custom Error';
      contentType = 'text/plain; charset=utf-8';
    }
    this.send(statusCode,content,contentType,statusMessage);
  }
  
  redirect(url){
    if(this.hasSent){
			debug(`response has redirect`);
      return;
    }
    this.hasSent = true;
    if(this.session){
      this.session.save().then(result=>{
        this._origin_response.redirect(url);
      }).catch(err=>{
				this.error(error.SESSION_SAVE_FAILED);
				debug(`session save error: `,err);
      });
    }else{
      this._origin_response.redirect(url);
    }
  }
  
  json(content){
    let [statusCode,contentType] = [200,'application/json; charset=utf-8'];
    this.send(statusCode,helper.stringify(content),contentType);
  }
  
  html(content){
    let [statusCode,contentType] = [200,'text/html; charset=utf-8'];
    this.send(statusCode,content,contentType);
  }
	
	text(content){
    let [statusCode,contentType] = [200,'text/plain; charset=utf-8'];
    this.send(statusCode,content,contentType);
  }
  
  ret(content = ''){
		if(this.restype === 'zdy'){
			let [statusCode,contentType] = [200,'text/plain; charset=utf-8'];
			if(content.code) statusCode = content.code;
			if(content.type) contentType = content.type;
			if(content.headers){
				for(let key in content.headers){
					this._origin_response.append(key,content.headers[key]);
				}
			}
			this.send(statusCode,content.body,contentType);
		}else if(this[this.restype]){
			this[this.restype](content);
		}else{
			this.send(content);
		}
  }
}

module.exports = Response;